﻿namespace MSRI.DesktopAgent.CeRapi
{
    using System;
    using System.Text;

    public class HelperClass
    {
        public static string GetSmartPhoneClient()
        {
            uint num;
            int lpType = 0;
            byte[] lpData = new byte[0x200];
            int lpchData = 0x200;
            string str = "";
            UnmanagedAPI.CeRapiInit();
            if ((UnmanagedAPI.CeRegOpenKeyEx(0x80000002, @"Software\MSRI\", 0, 1, out num) == 0) && (UnmanagedAPI.CeRegQueryValueEx(num, string.Empty, 0, ref lpType, lpData, ref lpchData) == 0))
            {
                str = Encoding.Unicode.GetString(lpData, 0, lpchData).Replace("\0", "");
            }
            UnmanagedAPI.CeRegCloseKey(num);
            UnmanagedAPI.CeRapiUninit();
            return str;
        }

        public static short GetTcpPort()
        {
            uint num;
            int lpType = 0;
            byte[] lpData = new byte[0x20];
            int lpchData = 0x20;
            short num4 = -1;
            UnmanagedAPI.CeRapiInit();
            if ((UnmanagedAPI.CeRegOpenKeyEx(0x80000002, @"Software\MSRI\", 0, 1, out num) == 0) && (UnmanagedAPI.CeRegQueryValueEx(num, "TcpPort", 0, ref lpType, lpData, ref lpchData) == 0))
            {
                num4 = Convert.ToInt16(Encoding.Unicode.GetString(lpData, 0, lpchData).Replace("\0", ""));
            }
            UnmanagedAPI.CeRegCloseKey(num);
            UnmanagedAPI.CeRapiUninit();
            return num4;
        }

        public static bool StartSmartPhoneClient()
        {
            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            string smartPhoneClient = GetSmartPhoneClient();
            int num = -1;
            UnmanagedAPI.CeRapiInit();
            if (smartPhoneClient == "")
            {
                num = UnmanagedAPI.CeCreateProcess(@"\Program Files\SMS Server Client\SMS Server Client.exe", string.Empty, IntPtr.Zero, IntPtr.Zero, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref pi);
            }
            else
            {
                num = UnmanagedAPI.CeCreateProcess(smartPhoneClient, string.Empty, IntPtr.Zero, IntPtr.Zero, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref pi);
            }
            UnmanagedAPI.CeRapiUninit();
            return (num > 0);
        }
    }
}

